import 'package:hinge/common/index.dart';
import 'package:hinge/common/values/index.dart';

class ChatService {
  static const String _chatSessionsKey = 'chat_sessions';
  static const String _chatMessagesKey = 'chat_messages';

  // 获取所有聊天会话
  static Future<List<ChatSessionModel>> getAllChatSessions() async {
    return SpUtil.getModelList<ChatSessionModel>(
      _chatSessionsKey,
      (json) => ChatSessionModel.fromJson(json),
    );
  }

  // 保存所有聊天会话
  static Future<void> saveAllChatSessions(
    List<ChatSessionModel> sessions,
  ) async {
    await SpUtil.setModelList(_chatSessionsKey, sessions);
  }

  // 创建三个示例群聊并保存
  static Future<void> createSampleGroupChats() async {
    // 创建三个群聊
    final List<ChatSessionModel> groupChats = [
      ChatSessionModel(
        id: 'group1',
        name: 'Woody Fragrances',
        type: ChatSessionType.group,
        memberIds: [6, 2, 3, 4, 5],
        avatar: AssetsImages.groupAvatar1,
      ),
      ChatSessionModel(
        id: 'group2',
        name: 'Floral Bouquets',
        type: ChatSessionType.group,
        memberIds: [4, 6, 7, 5],
        avatar: AssetsImages.groupAvatar2,
      ),
      ChatSessionModel(
        id: 'group3',
        name: 'Fresh Citrus',
        type: ChatSessionType.group,
        memberIds: [2, 5, 7, 6],
        avatar: AssetsImages.groupAvatar3,
      ),
    ];

    // 获取当前已有的会话
    List<ChatSessionModel> currentSessions = await getAllChatSessions();

    // 添加新创建的群聊
    currentSessions.addAll(groupChats);

    // 保存所有会话
    await saveAllChatSessions(currentSessions);

    // 创建并保存群聊消息
    await createSampleMessages();
  }

  // 创建示例消息
  static Future<void> createSampleMessages() async {
    List<ChatMessageModel> allMessages = [];

    // Woody Fragrances 群组消息
    allMessages.addAll([
      ChatMessageModel(
        id: 'msg1_woody',
        chatId: 'group1',
        senderId: 2,
        type: MessageType.text,
        text:
            "Has anyone tried Le Labo's Santal 33? It has amazing woody notes!",
        createdAt: DateTime.now().subtract(const Duration(days: 2, hours: 3)),
      ),
      ChatMessageModel(
        id: 'msg2_woody',
        chatId: 'group1',
        senderId: 3,
        type: MessageType.text,
        text:
            "I love Tom Ford's Oud Wood. The sandalwood and vetiver combination is perfect for winter.",
        createdAt: DateTime.now().subtract(const Duration(days: 2, hours: 2)),
      ),
      ChatMessageModel(
        id: 'msg3_woody',
        chatId: 'group1',
        senderId: 4,
        type: MessageType.text,
        text:
            "Diptyque's Tam Dao is my go-to woody scent. Cedar and sandalwood at its finest!",
        createdAt: DateTime.now().subtract(const Duration(days: 2, hours: 1)),
      ),
      ChatMessageModel(
        id: 'msg4_woody',
        chatId: 'group1',
        senderId: 5,
        type: MessageType.perfumeCard,
        perfumeCard: PerfumeModel(
          id: 1,
          category: 'Strong fragrance',
          userId: 1,
          title: 'Midnight Rose',
          description:
              'An intense floral scent with deep rose notes and a hint of spice. The luxurious blend opens with bergamot and black pepper, followed by a heart of Damascus rose and jasmine. The long-lasting base notes of patchouli and amber create an unforgettable aura of elegance.',
          isRecommend: true,
          isVideo: false,
          url: AssetsImages.strong1,
          cover: null,
          favoriteCount: 189,
          likeCount: 132,
          commentCount: 24,
        ),
        createdAt: DateTime.now().subtract(const Duration(days: 1, hours: 5)),
      ),
      ChatMessageModel(
        id: 'msg5_woody',
        chatId: 'group1',
        senderId: 6,
        type: MessageType.text,
        text:
            "Just discovered Byredo's Black Saffron and I'm obsessed with its woody undertones!",
        createdAt: DateTime.now().subtract(const Duration(hours: 12)),
      ),
    ]);

    // Floral Fragrances 群组消息
    allMessages.addAll([
      ChatMessageModel(
        id: 'msg1_floral',
        chatId: 'group2',
        senderId: 4,
        type: MessageType.text,
        text:
            "Jo Malone's Peony & Blush Suede is my absolute favorite for spring!",
        createdAt: DateTime.now().subtract(const Duration(days: 3, hours: 4)),
      ),
      ChatMessageModel(
        id: 'msg2_floral',
        chatId: 'group2',
        senderId: 7,
        type: MessageType.text,
        text:
            "I've been wearing Chanel's Chance Eau Tendre for years. The jasmine and rose combination is timeless.",
        createdAt: DateTime.now().subtract(const Duration(days: 3, hours: 3)),
      ),
      ChatMessageModel(
        id: 'msg3_floral',
        chatId: 'group2',
        senderId: 5,
        type: MessageType.perfumeCard,
        perfumeCard: PerfumeModel(
          id: 5,
          category: 'Eau de Toilette',
          userId: 5,
          title: 'Fresh Citrus',
          description:
              'A light and refreshing citrus blend, perfect for daytime wear. This invigorating scent opens with bright notes of Sicilian lemon, bergamot, and grapefruit, balanced with green notes of mint and basil. The heart reveals subtle floral accents of lavender and neroli, while the base of white musk provides a clean, lasting finish that is perfect for everyday elegance.',
          isRecommend: true,
          isVideo: false,
          url: AssetsImages.eau1,
          cover: null,
          favoriteCount: 142,
          likeCount: 96,
          commentCount: 15,
        ),
        createdAt: DateTime.now().subtract(const Duration(days: 2, hours: 6)),
      ),
      ChatMessageModel(
        id: 'msg4_floral',
        chatId: 'group2',
        senderId: 6,
        type: MessageType.text,
        text:
            "Anyone tried Gucci Bloom? I'm considering buying it for my sister's birthday.",
        createdAt: DateTime.now().subtract(const Duration(days: 1, hours: 2)),
      ),
      ChatMessageModel(
        id: 'msg5_floral',
        chatId: 'group2',
        senderId: 7,
        type: MessageType.text,
        text:
            "Marc Jacobs Daisy is such a classic floral fragrance. I always come back to it!",
        createdAt: DateTime.now().subtract(const Duration(hours: 5)),
      ),
    ]);

    // Citrus Fragrances 群组消息
    allMessages.addAll([
      ChatMessageModel(
        id: 'msg1_citrus',
        chatId: 'group3',
        senderId: 5,
        type: MessageType.text,
        text:
            "Atelier Cologne's Orange Sanguine is like a burst of fresh oranges. So refreshing!",
        createdAt: DateTime.now().subtract(const Duration(days: 4, hours: 7)),
      ),
      ChatMessageModel(
        id: 'msg2_citrus',
        chatId: 'group3',
        senderId: 2,
        type: MessageType.perfumeCard,
        perfumeCard: PerfumeModel(
          id: 9,
          category: 'Woody',
          userId: 1,
          title: 'Cedar Whisper',
          description:
              'Warm cedar notes with a touch of sandalwood for a sophisticated aura. This refined woody fragrance begins with fresh bergamot and cypress, evolving into a heart of Atlas cedar and aromatic juniper. The rich base of sandalwood, vetiver, and amber creates a warm, comforting embrace that evokes memories of ancient forests and secret woodland paths, perfect for those who appreciate timeless elegance.',
          isRecommend: true,
          isVideo: false,
          url: AssetsImages.woody1,
          cover: null,
          favoriteCount: 165,
          likeCount: 118,
          commentCount: 19,
        ),
        createdAt: DateTime.now().subtract(const Duration(days: 3, hours: 8)),
      ),
      ChatMessageModel(
        id: 'msg3_citrus',
        chatId: 'group3',
        senderId: 7,
        type: MessageType.text,
        text:
            "I really want to try Acqua di Parma's Fico di Amalfi. Has anyone here tried it?",
        createdAt: DateTime.now().subtract(const Duration(days: 2, hours: 10)),
      ),
      ChatMessageModel(
        id: 'msg4_citrus',
        chatId: 'group3',
        senderId: 6,
        type: MessageType.text,
        text:
            "Maison Margiela's Under the Lemon Trees takes me back to summer in Italy every time!",
        createdAt: DateTime.now().subtract(const Duration(days: 1, hours: 4)),
      ),
      ChatMessageModel(
        id: 'msg5_citrus',
        chatId: 'group3',
        senderId: 5,
        type: MessageType.text,
        text:
            "Jo Malone's Lime Basil & Mandarin is my signature scent. Perfect balance of citrus and herbs!",
        createdAt: DateTime.now().subtract(const Duration(hours: 3)),
      ),
    ]);

    // 保存所有消息
    await saveAllMessages(allMessages);
  }

  // 获取所有消息
  static Future<List<ChatMessageModel>> getAllMessages() async {
    return SpUtil.getModelList<ChatMessageModel>(
      _chatMessagesKey,
      (json) => ChatMessageModel.fromJson(json),
    );
  }

  // 保存所有消息
  static Future<void> saveAllMessages(List<ChatMessageModel> messages) async {
    await SpUtil.setModelList(_chatMessagesKey, messages);
  }

  // 获取特定聊天会话的消息
  static Future<List<ChatMessageModel>> getMessagesForChat(
    String chatId,
  ) async {
    List<ChatMessageModel> allMessages = await getAllMessages();
    return allMessages.where((msg) => msg.chatId == chatId).toList()
      ..sort((a, b) => a.createdAt.compareTo(b.createdAt));
  }

  // 根据ID获取聊天会话
  static Future<ChatSessionModel?> getChatSessionById(String id) async {
    List<ChatSessionModel> sessions = await getAllChatSessions();
    try {
      return sessions.firstWhere((session) => session.id == id);
    } catch (_) {
      return null;
    }
  }

  // 发送新消息
  static Future<ChatMessageModel> sendMessage({
    required String chatId,
    required int senderId,
    required MessageType type,
    String? text,
    PerfumeModel? perfumeCard,
  }) async {
    // 获取所有消息
    List<ChatMessageModel> allMessages = await getAllMessages();

    // 创建新消息
    final newMessage = ChatMessageModel(
      id: 'msg_${DateTime.now().millisecondsSinceEpoch}',
      chatId: chatId,
      senderId: senderId,
      type: type,
      text: text,
      perfumeCard: perfumeCard,
      createdAt: DateTime.now(),
    );

    // 添加新消息到列表
    allMessages.add(newMessage);

    // 保存所有消息
    await saveAllMessages(allMessages);

    return newMessage;
  }

  // 检查用户是否在群聊中
  static Future<bool> isUserInChat(String chatId, int userId) async {
    final chatSession = await getChatSessionById(chatId);
    if (chatSession == null) return false;

    return chatSession.memberIds.contains(userId);
  }

  // 将用户添加到群聊
  static Future<bool> addUserToChat(String chatId, int userId) async {
    // 获取所有会话
    List<ChatSessionModel> allSessions = await getAllChatSessions();

    // 查找指定的会话
    int sessionIndex = allSessions.indexWhere(
      (session) => session.id == chatId,
    );
    if (sessionIndex == -1) return false;

    // 检查用户是否已在群聊中
    if (allSessions[sessionIndex].memberIds.contains(userId)) {
      return true; // 用户已在群聊中
    }

    // 创建新的会话对象，添加用户ID到成员列表
    final updatedSession = ChatSessionModel(
      id: allSessions[sessionIndex].id,
      name: allSessions[sessionIndex].name,
      type: allSessions[sessionIndex].type,
      memberIds: [...allSessions[sessionIndex].memberIds, userId],
      avatar: allSessions[sessionIndex].avatar,
    );

    // 更新会话列表
    allSessions[sessionIndex] = updatedSession;

    // 保存更新后的会话列表
    await saveAllChatSessions(allSessions);

    return true;
  }

  // 查找或创建私聊会话
  static Future<ChatSessionModel> findOrCreatePrivateChat(
    int currentUserId,
    int targetUserId,
  ) async {
    // 获取所有聊天会话
    final sessions = await getAllChatSessions();

    // 查找是否已存在私聊会话
    final existingChat = sessions.firstWhere(
      (session) =>
          session.type == ChatSessionType.private &&
          session.memberIds.length == 2 &&
          session.memberIds.contains(currentUserId) &&
          session.memberIds.contains(targetUserId),
      orElse:
          () => ChatSessionModel(
            id: '', // 空ID表示需要创建新会话
            name: '',
            type: ChatSessionType.private,
            memberIds: [],
            avatar: '',
          ),
    );

    // 如果找到现有会话，直接返回
    if (existingChat.id.isNotEmpty) {
      return existingChat;
    }

    // 获取目标用户信息
    final targetUser = UserService.getUserById(targetUserId);
    if (targetUser == null) {
      throw Exception('Target user not found');
    }

    // 创建新的私聊会话
    final newChat = ChatSessionModel(
      id: 'private_${DateTime.now().millisecondsSinceEpoch}',
      name: targetUser.nickname,
      type: ChatSessionType.private,
      memberIds: [currentUserId, targetUserId],
      avatar: targetUser.avatar,
    );

    // 保存新会话
    sessions.add(newChat);
    await saveAllChatSessions(sessions);

    return newChat;
  }
}
